<?php

namespace app\controller;

use app\BaseController;
use think\App;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db as db;
use think\Model;
use think\Request;
use app\utils\simple_html_dom;
use Xhat\Payjs\Payjs;


class Hello extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);

    }


    public function logout()
    {
        session(null);  //清空session
        return redirect('/');
    }

    public function img_free()
    {
        $cache = Cache::store('redis');
        $arr = [];
        $list = $this->projectModel->select();
        foreach ($list as $project) {
            $html = new simple_html_dom();
            $html->load($project->content);
            foreach($html->find('img') as $img){
                if (strpos($img->src, 'http://res.itsub.cn') === false) {
                    continue; //不是itsub的图片不予处理
                }
                $filename = basename($img->src);
                $suffix = substr(strrchr($filename, '.'), 1);
                $name = basename($filename,".".$suffix); //md5名字
                $key = 'img:'.$name;
                $cache->tag('imgs')->set($key, 1, 3600);

            }
        }

        $items = $cache->getTagItems('imgs');
        foreach ($items as $item) {
            $md5 = substr($item,4);
            array_push($arr, $md5);
        }

        $free = [];
        foreach(Db::table('img')->select() as $row){
            $txt = $row['md5'];
            if (in_array($txt, $arr)) {
                //echo $txt.'[pass]<br>';
            }else{
                //echo $txt.'<br>';
                array_push($free, $txt);
            }
        }

        return json_encode(['code'=>0, 'msg' => '查询成功', 'data'=>$free],JSON_UNESCAPED_UNICODE);

    }

    /**
     * 图片上传(ajax)
     * @return \think\Response|void
     * @throws \Exception
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('imgFile');
        try{
            // 验证
            validate(['imgFile'=>[
                'fileSize' => 410241024,
                'fileExt' => 'jpg,jpeg,png,bmp,gif',
                'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上，很重要我认为！
            ]])->check(['imgFile' => $file]);

            // 上传图片到本地服务器
            $saveName = \think\facade\Filesystem::disk('public')->putFile( 'merchant', $file, 'data');
            $this->result(1, '图片上传成功!', $saveName, 'json');
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->exceptionHandle($e,
                '图片上传失败!' . $e->getMessage(),
                'json',
                '');
        }
    }





}
